from flask import Blueprint, jsonify, request
from models.entity.device_group import DeviceGroup
from models.entity.device import Device
import json
from utils.result import result

mod = Blueprint("core_device_group", __name__, url_prefix="/core/device_group", template_folder="templates", static_folder="static")

@mod.route('/add/',methods=['POST'])
def add_device_type():
    """增加设备组"""
    """
   {

    "name":"dd5",
    "code":"2dddd",
    "description":"22222",
    "icon":"abc"
    }
    """
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        if 'id' in dict:
            dict.pop('id')
        if DeviceGroup.get_device_group_by_name(dict['name']) is not None:
            return result(success=0,error_code=-2,error_msg="设备组的名称已存在")
        if DeviceGroup.get_device_group_by_code(dict['code']) is not None:
            return result(success=0, error_code=-2, error_msg="设备组的编码已存在")
        device_group = DeviceGroup()
        try:
            device_group.from_dict(dict)
        except RuntimeError as err:
            return result(success=0, error_code=-2, error_msg=str(err))
        if device_group.save():
            return result(success=1)
        else:
            return result(success=0,error_msg='未知错误',error_code=-3)



@mod.route('/edit/', methods=['POST'])
def edit_device_group():
    """编辑设备组"""
    """
    {
    "id":1,
    "name":"0",
    "code":"25",
    "icon":"22",
    "description":"22222"
    }
    """
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = dict['id']
        device_group= DeviceGroup.get_device_group_by_id(id)
        if "device_num" in dict:
            dict.pop("device_num")
        try:
            device_group.from_dict(dict)
        except RuntimeError as e:
            return result(success=0,error_code=-2,error_msg='格式错误')
        if dict['name'] != device_group.name and DeviceGroup.get_device_group_by_name(dict['name']):
            return result(success=0,error_code=-2,error_msg='名称已经存在')
        if dict['code'] != device_group.code and DeviceGroup.get_device_group_by_code(dict['code']):
            return result(success=0, error_code=-2, error_msg='设备分组的编码已存在')
        if device_group.save():
            return result(success=1)
        else:
            return result(success=0, error_code=-2, error_msg='设备分组的编码已存在')

@mod.route('/del/', methods=['POST'])
def del_device_group():
    """删除指定id的设备组"""
    """
    {
    "id":1
    }

    """
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = dict['id']
        device_group = DeviceGroup.get_device_group_by_id(id)
        if len(Device.get_devices_by_group_id(id))!=0:
            return result(success=0,error_code=-1,error_msg="设备分组下存在子设备，不能删除")
        if device_group.delete():
            return result(success=1)
        else:
            return result(success=0,error_code=-2,error_msg="未知错误")


@mod.route('/get_all/', methods=['POST', 'GET'])
def get_device_group():
    """
    以列表形式获取所有设备组
    """
    if request.method == 'POST':
        data =[]
        device_groups = DeviceGroup().get_list_all()
        # print('device_groups', device_groups)
        for item in device_groups:
            data.append(item.get_dic())
        return result(success=1, data=data)

@mod.route("/search/",methods=["POST"])
def search_device_group():
    """
    模糊查询
    """
    # request: json
    # {
    #      "query_word": "lishimin"
    # }
    if request.method == 'POST':
        receive = request.data
        data = json.loads(receive.decode("utf-8"))
        tmp ={}
        extra =[]
        if 'query_word' in data:
            query_word = data['query_word']
        else:
            tmp['success'] = 0
            tmp['error_code'] = -9
            tmp['error_msg'] = "数据格式错误"
            tmp['data'] = extra
            return result(success=0,error_code=-9,error_msg='数据格式错误')
        device_groups = DeviceGroup.search(query_word)
        return result(data=device_groups)
